<?php

namespace App\Http\Logic\Admin;

use App;
use App\Common\Status;
use App\Models\Business;
use \App\Models\BusinessAddress;
use App\Helper\Helper;
use Illuminate\Support\Facades\DB;

class BusinessLogic
{

    /**
     * @param $params
     * @param $pageSize
     * @param $page
     * @return array
     */
    public static function getBusinessList($params, $pageSize, $page)
    {
        $where[] = ['a.status', '=', Status::REGULAR];
        $where[] = ['a.is_deleted', '=', Status::NOT_DELETE];

        if (isset($params['name']) && $params['name']) {
            $where[] = ['a.name', 'like', '%' . $params['name'] . '%'];
        }
        if (isset($params['type']) && $params['type']) {
            $where[] = ['a.type', '=', $params['type']];
        }
        if (isset($params['show']) && $params['show']) {
            $where[] = ['a.type', '=', $params['type']];
        }
        if (isset($params['st_dt']) && $params['st_dt']) {
            $where[] = ['a.created_at', '>=', strtotime($params['st_dt'])];
        }
        if (isset($params['en_dt']) && $params['en_dt']) {
            $where[] = ['a.created_at', '<=', strtotime($params['en_dt'])];
        }
        if (isset($params['scale']) && $params['scale']) {
            $where[] = ['a.scale', '=', $params['scale']];
        }
        if (isset($params['hot']) && $params['hot']) {
            $where[] = ['a.hot', '=', $params['hot']];
        }
        $field = ["a.id", "a.name", "a.short_name", "a.logo", "a.scale", "a.type", "a.content", "a.hot", "a.show", "a.status", "a.created_at", "b.path as logo_path"];
        $data  = DB::table('recruit_business as a')
            ->leftJoin('recruit_resources as b', function ($join) {
                $join->on("a.logo", "=", "b.id")
                    ->where("b.status", '=', Status::REGULAR)
                    ->where("b.is_deleted", '=', Status::NOT_DELETE);
            })->select($field)
            ->where($where)
            ->orderBy("a.created_at", "desc")
            ->offset($pageSize * ($page - 1))
            ->limit($pageSize)
            ->get();

        $count = self::getCount($where);
        $data  = self::getDataInfo($data);
        return ['list' => $data, 'total' => $count, 'page' => $page, 'pageSize' => $pageSize];
    }

    private static function getCount($where)
    {
        return DB::table('recruit_business as a')
            ->leftJoin('recruit_resources as b', function ($join) {
                $join->on("a.logo", "=", "b.id")
                    ->where("b.status", '=', Status::REGULAR)
                    ->where("b.is_deleted", '=', Status::NOT_DELETE);
            })
            ->where($where)->count();
    }

    /**
     * @param $params
     * @return mixed
     * @throws \Exception
     */
    public static function createBusiness($params)
    {
        $address = $params['address'];
        unset($params['address']);

        $connection = DB::connection('mysql');

        $connection->beginTransaction();
        try {
            if ($params['id']) {
                $id = $params['id'];

                self::createAddress($id, $address);

                $params['updated_at'] = time();

                unset($params['id']);

                Business::where('id', $id)->update($params);

                $connection->commit();

                return true;
            }
            $params['created_at'] = time();
            $params['creator_id'] = Helper::adminById();

            $id = Business::insertGetId($params);

            self::createAddress($id, $address);

            $connection->commit();

            return $id;
        } catch (\Exception $exception) {
            DB::rollBack();

            throw new \Exception($exception->getMessage());
        }
    }


    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    public function getBusinessDtl($id)
    {
        $field = ["a.id", "a.name", "a.short_name", "a.logo","a.logo2", "a.scale", "a.type", "a.content", "a.hot", "a.show",
            "a.status", "a.created_at", "b.path as logo_path"];
        $binfo = DB::table('recruit_business as a')
            ->leftJoin('recruit_resources as b', function ($join) {
                $join->on("a.logo", "=", "b.id")
                    ->where("b.status", '=', Status::REGULAR)
                    ->where("b.is_deleted", '=', Status::NOT_DELETE);
            })->select($field)
            ->where("a.id", $id)
            ->first();

        if ($binfo) {
            $binfo->logo_path2 = "";

            if($binfo->logo2) {
                $logo_path2 = DB::table('recruit_resources')->where("id",$binfo->logo2)->first();
                if ($logo_path2) {
                    $binfo->logo_path2 = $logo_path2->path;
                }
            }

            $binfo->address = BusinessAddress::select(["city", "area", "address"])->where(
                [
                    ["status", '=', Status::REGULAR],
                    ["is_deleted", '=', Status::NOT_DELETE],
                    ["business_id", '=', $id]
                ])->get();
        }
        return self::getDataInfo([$binfo]);
    }


    /**
     * 企业详情
     * @param $data
     * @return mixed
     */
    private static function getDataInfo($data)
    {
        foreach ($data as $datum) {
            $datum->hot_info  = $datum->hot == 1 ? '否' : '是';
            $datum->show_info = $datum->show == 1 ? '隐藏' : '2展示';
//            $datum->scale     = Status::BUSINESS_SCALE[$datum->scale];
//            $datum->type      = Status::BUSINESS_TYPE[$datum->type];

            # 获取资源
            $datum->logo_path = Helper::buildQiNiuUrl($datum->logo_path);
            if (isset($datum->logo_path2) && $datum->logo_path2) {
                $datum->logo_path2 = Helper::buildQiNiuUrl($datum->logo_path2) ;
            }
        }
        return $data;
    }

    /**
     * @param $bid
     * @param $address
     */
    private static function createAddress($bid, $address)
    {
        if ($bid) {
            BusinessAddress::where('business_id', $bid)->update(
                [
                    'status'     => Status::NOT_DELETE,
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
        }
        if ($address && count($address) > 0) {
            foreach ($address as &$addr) {
                $area_name        = DB::table('recruit_city')->select("name")->where("id", $addr['area'])->first();
                $city_name        = DB::table('recruit_city')->select(["parentid", "name"])->where("id", $addr['city'])
                    ->first();
                $addr['area_name'] = $area_name ? $area_name->name : '';
                $addr['city_name'] = $city_name ? $city_name->name : '';
                $addr['business_id'] = $bid;
                $addr['created_at']  = time();
                $addr['creator_id']  = Helper::adminById();
            }
            BusinessAddress::insert($address);
        }
    }


    /**
     * @param $id
     * @return mixed
     */
    public static function delBusiness($id)
    {
        return Business::where('id', $id)->update(
            [
                'status'     => Status::NOT_DELETE,
                'is_deleted' => Status::DELETED,
                'deleted_at' => time()
            ]
        );
    }


    /**
     * @param $id
     * @param $type
     * @return mixed
     */
    public static function setStatus($id, $type)
    {
        $c = Business::select("hot", "show")->find($id);
        if ($type == 1) {
            $hot = $c->hot == 1 ? 2 : 1;
            return Business::where('id', $id)->update(['hot' => $hot, 'updated_at' => time()]);
        } else {
            $show = $c->show == 1 ? 2 : 1;
            return Business::where('id', $id)->update(['show' => $show, 'updated_at' => time()]);
        }
    }
}
